package com.exchange; 

import com.exchange.CardManger.Listener;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; 
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements Listener {  
	
    BluetoothAdapter adapter;
    boolean isEnable;
    String btName;
    BTBroadcastReceiver receiver;
    boolean isFound;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter = BluetoothAdapter.getDefaultAdapter();
        isEnable = adapter.isEnabled();
        adapter.enable(); 
        btName = adapter.getName(); 
        ((Button)findViewById(R.id.exchange)).setOnClickListener( new OnClickListener() { 
			public void onClick(View v) { 
				search();
			}
		});
        
        receiver = new BTBroadcastReceiver(); 
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(receiver, filter); 
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(receiver, filter);
        
        CardManger.getInstance().setListener(this); 
    }
    
    protected void onDestroy() {
    	super.onDestroy();
    	adapter.cancelDiscovery();
    	adapter.setName(btName); 
    	if( !isEnable ){
    		adapter.disable();
    	}
    	this.unregisterReceiver(receiver);
    }
    
    void search(){
    	isFound = false;
    	
    	String name = ((EditText)findViewById(R.id.name)).getText().toString();
    	String phone = ((EditText)findViewById(R.id.phone)).getText().toString();
    	
    	adapter.setName( CardManger.gererateName( name, phone )); 
    	 
    	startDiscoverable();
     
        ((TextView)findViewById(R.id.receive)).setText("finding...");
    } 

	
    void startDiscoverable() { 
    	if( adapter.isDiscovering() ){
    		adapter.cancelDiscovery();
    	}
    	   adapter.startDiscovery(); 
//        if (adapter.getScanMode() !=
//            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {

		Intent discoverableIntent = new Intent(
				BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		discoverableIntent.putExtra(
				BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60 * 1000);
		startActivity(discoverableIntent);
    }

 
	public void find( final String info) { 
		runOnUiThread( new Runnable() { 
			public void run() {
				isFound = true;
				((TextView)findViewById(R.id.receive)).setText(info);
			}
		}); 
	}

	@Override
	public void searchFinish() { 
		runOnUiThread( new Runnable() { 
			public void run() {
				if (!isFound) { 
					adapter.startDiscovery();
				}
			}
		});
	}
}